package club.zbiao.modules.system.service.spec;

import club.zbiao.modules.system.domain.Menu;
import club.zbiao.modules.system.service.dto.MenuDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhb on 2019/5/23.
 */
@Component
public class MenuSpec implements BaseSpec<MenuDTO, Menu> {

    private String name;

    public void init(MenuDTO menuDTO) {
        this.name = menuDTO.getName();
    }

    @Override
    public Predicate toPredicate(Root<Menu> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

        List<Predicate> list = new ArrayList<Predicate>();

        if (!ObjectUtils.isEmpty(name)) {
            list.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
        }

        Predicate[] p = new Predicate[list.size()];
        return cb.and(list.toArray(p));
    }
}
